import { app, BrowserWindow, ipcMain, dialog } from 'electron'
const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs');
const path = require('path');


/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
    global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`

function createWindow() {
    /**
     * Initial window options
     */
    mainWindow = new BrowserWindow({
        height: 563,
        useContentSize: true,
        width: 1000,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        }
    })

    mainWindow.loadURL(winURL)

    mainWindow.on('closed', () => {
        mainWindow = null
    })

    // 消除工具栏
    mainWindow.setMenuBarVisibility(false)
}

// if you want load native module like serialport set follow code
// app.allowRendererProcessReuse = false 
app.on('ready', createWindow)

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow()
    }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */

// 指定 ffmpeg 的路径
if (process.env.NODE_ENV === 'development') {
    const ffmpegPath = path.join(__dirname, 'lib', 'ffmpeg.exe'); // 替换为你的 ffmpeg 可执行文件的实际路径
    ffmpeg.setFfmpegPath(ffmpegPath);
} else {
    const ffmpegPath = path.join(process.resourcesPath, 'lib', 'ffmpeg.exe'); // 替换为你的 ffmpeg 可执行文件的实际路径
    ffmpeg.setFfmpegPath(ffmpegPath);
}

// Handle watermark removal from IPC
ipcMain.handle('remove-watermark', async (event, videoPath, marks, canGpu) => {
    // 提取文件名
    const fileName = path.basename(videoPath);
    let outputFilePath;
    if (process.env.NODE_ENV === 'development') {
        outputFilePath = path.join(__dirname, fileName);
    } else {
        outputFilePath = path.join(process.resourcesPath, fileName);
    }
    if (!videoPath || marks.length <= 0) {
        throw new Error('Video path or mark is missing');
    }
    try {
        // 分类标记
        const hasRangeMarks = marks.filter(mark => mark.isHasRangeTime); // 带时间范围的标记
        const fullRangeMarks = marks.filter(mark => !mark.isHasRangeTime); // 全时间范围的标记
        // 构建 delogo 滤镜字符串
        const delogoFilters = [
            ...hasRangeMarks.map(mark => 
                `delogo=x=${mark.startX}:y=${mark.startY}:w=${mark.width}:h=${mark.height}:enable='between(t,${mark.startTime},${mark.endTime})'`
            ),
            ...fullRangeMarks.map(mark => 
                `delogo=x=${mark.startX}:y=${mark.startY}:w=${mark.width}:h=${mark.height}`
            )
        ].join(',');
        if (canGpu) {
            // 使用 GPU 加速进行编码
            await new Promise((resolve, reject) => {
                ffmpeg(videoPath)
                    .inputOptions('-hwaccel cuda') // 启用 CUDA 硬件加速
                    .output(outputFilePath)
                    .videoFilter(delogoFilters) // 应用 delogo 滤镜
                    .outputOptions('-c:v h264_nvenc') // 使用 NVIDIA H.264 编码器
                    .outputOptions('-b:v 2M') // 设置视频比特率
                    .on('progress', (progress) => {
                        // 使用 event.sender.send 发送进度更新
                        event.sender.send('ffmpeg-progress', progress.percent);
                    })
                    .on('end', resolve) // 处理完成时触发
                    .on('error', reject) // 处理错误时触发
                    .run();
            });
        } else {
            // 使用 ffmpeg 处理本地文件
            await new Promise((resolve, reject) => {
                ffmpeg(videoPath)
                    .output(outputFilePath)
                    .videoFilter(delogoFilters)
                    .on('progress', (progress) => {
                        // 使用 event.sender.send 发送进度更新
                        event.sender.send('ffmpeg-progress', progress.percent);
                    })
                    .on('end', resolve)
                    .on('error', reject)
                    .run();
            });
        }
        return outputFilePath;
    } catch (err) {
        console.error('Error removing watermark:', err);
        throw err;
    }
});

// 监听来自渲染进程的请求
ipcMain.handle('open-file-dialog', async (event) => {
    const result = await dialog.showOpenDialog({
        properties: ['openFile'],
        filters: [{ name: 'Videos', extensions: ['mp4', 'avi', 'mov'] }],
    });

    if (!result.canceled && result.filePaths.length > 0) {
        return result.filePaths[0]; // 返回文件路径
    }
    return null; // 如果用户取消选择，返回 null
});


// Handle directory selection from IPC
ipcMain.handle('select-directory', async (event) => {
    try {
        const result = await dialog.showOpenDialog(mainWindow, {
            properties: ['openDirectory'],
            title: '选择保存输出视频的路径' // 添加标题提示
        });
        if (!result.canceled && result.filePaths.length > 0) {
            return result.filePaths[0];
        } else {
            return null;
        }
    } catch (err) {
        console.error('Error selecting directory:', err);
        throw err;
    }
});


// Handle save video from IPC
ipcMain.handle('save-video', async (event, filePath, fileDirectory) => {
    try {
        if (!filePath || !fileDirectory) {
            throw new Error('File path or directory path is missing');
        }
        const fileName = path.basename(filePath);
        const destinationPath = path.join(fileDirectory, fileName);
        // 复制文件
        fs.copyFileSync(filePath, destinationPath);

        console.log('Video saved successfully:', destinationPath);
        return destinationPath;
    } catch (err) {
        console.error('Error saving video:', err);
        throw err;
    }
});


// Handle file deletion from IPC
ipcMain.handle('delete-file', async (event, filePath) => {
    try {
        if (!filePath) {
            throw new Error('File path is missing');
        }
        fs.unlinkSync(filePath);
        console.log('File deleted successfully:', filePath);
        return true;
    } catch (err) {
        console.error('Error deleting file:', err);
        throw err;
    }
});